package com.konsung.ksdc.manager.shop;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.AfterSaleNetBean;
import com.konsung.ksdc.bean.netbean.ExpressDetailNetBean;
import com.konsung.ksdc.bean.netbean.OrderProductNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.widget.OnMultiClickListener;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.manager.appmain.BaseActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 退换货详情
 * Created by DJH on 2017/3/8 0008.
 */

public class ReturnsDetailActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tab_tv_title)
    TextView tvTitle;
    @Bind(R.id.ll_apply)
    LinearLayout llApply;
    @Bind(R.id.ll_check)
    LinearLayout llCheck;
    @Bind(R.id.rl_success)
    RelativeLayout rlSuccess;
    @Bind(R.id.iv_returns_status)
    ImageView ivReturnsStatus;
    @Bind(R.id.tv_returns_status)
    TextView tvReturnsStatus;
    @Bind(R.id.tv_returns_type)
    TextView tvReturnsType;
    @Bind(R.id.tv_success_time)
    TextView tvSuccessTime;
    @Bind(R.id.tv_returns_address)
    TextView tvReturnsAddress;
    @Bind(R.id.tv_returns_reason)
    TextView tvReturnsReason;
    @Bind(R.id.tv_apply_time)
    TextView tvApplyTime;
    @Bind(R.id.ll_express_info)
    LinearLayout llExpressInfo;
    @Bind(R.id.et_express_name)
    EditText etExpressName;
    @Bind(R.id.et_express_num)
    EditText etExpressNum;
    @Bind(R.id.btn_confirm)
    Button btnConfirm;
    @Bind(R.id.ll_returns_address)
    LinearLayout llReturnsAddress;
    @Bind(R.id.ll_apply_info)
    LinearLayout llApplyInfo;
    @Bind(R.id.tv_residue_time)
    TextView tvResidueTime;

    public static final String PRODUCT_TYPE_RETURNS = "4";
    public static final String PRODUCT_TYPE_EXCHANGE = "3";
    private String orderProductId;
    private AfterSaleNetBean afterSaleNetBean;
    private OrderProductNetBean orderProductNetBean;
    private ExpressDetailNetBean expressReturnsBean;
    private ExpressDetailNetBean expressExchangeBean;
    private String returnsStatus;
    private String returnsType;
    private WaitingDialog dialog;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshReturnsStatus();
            refreshReturnsInfo();
        }
    };

    @Override
    protected String activityDesc() {
        return getString(R.string.returning);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_returns_detail);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    /**
     * 初始化退换货流程数据
     */
    private void initData() {
        orderProductId = getIntent().getStringExtra(OrderBuyListAdapter.ORDER_PRODUCT_ID);
        orderProductNetBean = getIntent().getParcelableExtra(OrderBuyListAdapter
                .ORDER_PRODUCT_BEAN);
        findAfterDetail(orderProductNetBean);
    }

    /**
     * 获取退换货详情信息
     * @param orderProductNetBean 商品详情bean
     */
    private void findAfterDetail(OrderProductNetBean orderProductNetBean) {
        List<ExpressDetailNetBean> expressDetailNetBeanList = orderProductNetBean
                .getShipments();
        if (null != expressDetailNetBeanList && expressDetailNetBeanList.size() > 0) {
            for (ExpressDetailNetBean bean : expressDetailNetBeanList) {
                if (PRODUCT_TYPE_RETURNS.equals(bean.getShipmentType())) {
                    expressReturnsBean = bean;
                } else if (PRODUCT_TYPE_EXCHANGE.equals(bean.getShipmentType())) {
                    expressExchangeBean = bean;
                }
            }
        }
        RequestUtils.findAfterDetail(orderProductId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {

            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                if (Constants.REQUEST_OK.equals(responseBean.getResultCode())) {
                    afterSaleNetBean = responseBean.getEntity(AfterSaleNetBean.class);
                    returnsStatus = afterSaleNetBean.getStatus();
                    handler.sendEmptyMessage(0);
                }
            }
        });
    }

    /**
     * 初始化退换货流程界面
     */
    private void initView() {
        rlBack.setOnClickListener(this);
        btnConfirm.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                submitReturnsInfo();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 提交退换货信息
     */
    private void submitReturnsInfo() {
        String expressName = etExpressName.getText().toString();
        String expressNum = etExpressNum.getText().toString();
        if (TextUtils.isEmpty(expressName)) {
            Toast.makeText(this, R.string.x_edit_express_name, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(expressNum)) {
            Toast.makeText(this, R.string.x_edit_express_num, Toast.LENGTH_SHORT).show();
            return;
        }
        dialog = new WaitingDialog(ReturnsDetailActivity.this, "");
        dialog.setText(getString(R.string.submitting));
        dialog.show();
        RequestUtils.goodSentBack(orderProductId, expressName, expressNum, returnsType,
                new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        Toast.makeText(ReturnsDetailActivity.this, R.string.tip_server_error, Toast
                                .LENGTH_SHORT).show();
                        dialog.dismiss();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        dialog.dismiss();
                        if (Constants.REQUEST_OK.equals(responseBean.getResultCode())) {
                            Toast.makeText(ReturnsDetailActivity.this, R.string.submit_success,
                                    Toast.LENGTH_SHORT).show();
                            getExpressInfo();
                        }
                    }
                });
    }

    /**
     * 获取物流信息
     */
    private void getExpressInfo() {
        RequestUtils.findOrderProById(orderProductId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {

            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                if (Constants.REQUEST_OK.equals(responseBean.getResultCode())) {
                    orderProductNetBean = responseBean.getEntity(OrderProductNetBean.class);
                    findAfterDetail(orderProductNetBean);
                }
            }
        });
    }

    /**
     * 根据退换货状态刷新界面
     */
    private void refreshReturnsStatus() {
        /**
         * 订单商品状态
         *(1、正常,2、退货中，3、换货中，4、退货成功，5、换货成功,6、已取消
         *7、申请退货，8、申请换货, 9、退-审核通过,0、换-审核通过)
         */
        switch (returnsStatus) {
            case Constants.PRODUCT_TYPE_NORMAL:
                break;
            case Constants.PRODUCT_TYPE_REQUEST_REFUND:
                tvTitle.setText(R.string.cb_back);
                llApply.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                rlSuccess.setVisibility(View.GONE);
                ivReturnsStatus.setImageResource(R.drawable.ic_returns_check);
                tvReturnsStatus.setText(R.string.wait_check);
                llReturnsAddress.setVisibility(View.GONE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.GONE);
                btnConfirm.setVisibility(View.GONE);
                returnsType = PRODUCT_TYPE_RETURNS;
                break;
            case Constants.PRODUCT_TYPE_REFUND_CHECKED:
                tvTitle.setText(R.string.cb_back);
                llApply.setVisibility(View.GONE);
                llCheck.setVisibility(View.VISIBLE);
                rlSuccess.setVisibility(View.GONE);
                llReturnsAddress.setVisibility(View.VISIBLE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.VISIBLE);
                btnConfirm.setVisibility(View.VISIBLE);
                etExpressName.setEnabled(true);
                etExpressNum.setEnabled(true);
                returnsType = PRODUCT_TYPE_RETURNS;
                break;
            case Constants.PRODUCT_TYPE_REFUNDING:
                tvTitle.setText(R.string.cb_back);
                llApply.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                rlSuccess.setVisibility(View.GONE);
                ivReturnsStatus.setImageResource(R.drawable.ic_product_returning);
                tvReturnsStatus.setText(R.string.product_returning);
                llReturnsAddress.setVisibility(View.VISIBLE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.VISIBLE);
                btnConfirm.setVisibility(View.GONE);
                if (null != expressReturnsBean) {
                    etExpressName.setText(expressReturnsBean.getExpressCompany());
                    etExpressNum.setText(expressReturnsBean.getExpressCode());
                }
                etExpressName.setEnabled(false);
                etExpressNum.setEnabled(false);
                returnsType = PRODUCT_TYPE_RETURNS;
                break;
            case Constants.PRODUCT_TYPE_REFUNDING_SUCCESS:
                tvTitle.setText(R.string.btn_refund_success);
                llApply.setVisibility(View.GONE);
                llCheck.setVisibility(View.GONE);
                rlSuccess.setVisibility(View.VISIBLE);
                tvReturnsType.setText(R.string.btn_refund_success);
                llReturnsAddress.setVisibility(View.VISIBLE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.VISIBLE);
                btnConfirm.setVisibility(View.GONE);
                if (null != expressReturnsBean) {
                    etExpressName.setText(expressReturnsBean.getExpressCompany());
                    etExpressNum.setText(expressReturnsBean.getExpressCode());
                }
                etExpressName.setEnabled(false);
                etExpressNum.setEnabled(false);
                returnsType = PRODUCT_TYPE_RETURNS;
                break;
            case Constants.PRODUCT_TYPE_REQUEST_EXCHANGE:
                tvTitle.setText(R.string.cb_exchange);
                llApply.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                rlSuccess.setVisibility(View.GONE);
                ivReturnsStatus.setImageResource(R.drawable.ic_returns_check);
                tvReturnsStatus.setText(R.string.wait_check);
                llReturnsAddress.setVisibility(View.GONE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.GONE);
                btnConfirm.setVisibility(View.GONE);
                returnsType = PRODUCT_TYPE_EXCHANGE;
                break;
            case Constants.PRODUCT_TYPE_EXCHANGE_CHECKED:
                tvTitle.setText(R.string.cb_exchange);
                llApply.setVisibility(View.GONE);
                llCheck.setVisibility(View.VISIBLE);
                rlSuccess.setVisibility(View.GONE);
                llReturnsAddress.setVisibility(View.VISIBLE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.VISIBLE);
                btnConfirm.setVisibility(View.VISIBLE);
                etExpressName.setEnabled(true);
                etExpressNum.setEnabled(true);
                returnsType = PRODUCT_TYPE_EXCHANGE;
                break;
            case Constants.PRODUCT_TYPE_EXCHANGING:
                tvTitle.setText(R.string.cb_exchange);
                llApply.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                rlSuccess.setVisibility(View.GONE);
                ivReturnsStatus.setImageResource(R.drawable.ic_product_returning);
                tvReturnsStatus.setText(R.string.product_returning);
                llReturnsAddress.setVisibility(View.VISIBLE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.VISIBLE);
                btnConfirm.setVisibility(View.GONE);
                if (null != expressExchangeBean) {
                    etExpressName.setText(expressExchangeBean.getExpressCompany());
                    etExpressNum.setText(expressExchangeBean.getExpressCode());
                }
                etExpressName.setEnabled(false);
                etExpressNum.setEnabled(false);
                returnsType = PRODUCT_TYPE_EXCHANGE;
                break;
            case Constants.PRODUCT_TYPE_EXCHANGING_SUCCESS:
                tvTitle.setText(R.string.btn_exchanging_success);
                llApply.setVisibility(View.GONE);
                llCheck.setVisibility(View.GONE);
                rlSuccess.setVisibility(View.VISIBLE);
                tvReturnsType.setText(R.string.btn_exchanging_success);
                llReturnsAddress.setVisibility(View.VISIBLE);
                llApplyInfo.setVisibility(View.VISIBLE);
                llExpressInfo.setVisibility(View.VISIBLE);
                btnConfirm.setVisibility(View.GONE);
                if (null != expressExchangeBean) {
                    etExpressName.setText(expressExchangeBean.getExpressCompany());
                    etExpressNum.setText(expressExchangeBean.getExpressCode());
                }
                etExpressName.setEnabled(false);
                etExpressNum.setEnabled(false);
                returnsType = PRODUCT_TYPE_EXCHANGE;
                break;
            case Constants.PRODUCT_TYPE_CANCELED:
                break;
            default:
                break;
        }
    }

    /**
     * 刷新退换货信息
     */
    private void refreshReturnsInfo() {
        tvReturnsAddress.setText(afterSaleNetBean.getSentBackAddress());
        tvApplyTime.setText(afterSaleNetBean.getRequestTime());
        tvReturnsReason.setText(afterSaleNetBean.getReason());
        tvSuccessTime.setText(afterSaleNetBean.getConfirmTime());
        tvResidueTime.setText(calculateResidueTime());
    }

    /**
     * 计算退换货剩余时间
     * @return 时间字符串
     */
    private String calculateResidueTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            long currentTime = new Date().getTime();
            if (!TextUtils.isEmpty(afterSaleNetBean.getAgreeTime())) {
                long time = simpleDateFormat.parse(afterSaleNetBean.getAgreeTime()).getTime();
                long residueTime = 86400000 * 7 - currentTime + time; // 7天倒计时
                if (residueTime >= 0) {
                    long day = residueTime / 86400000;
                    long hour = residueTime % 86400000 / 3600000;
                    return day + getString(R.string.day) + hour + getString(R.string.hour);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }
}
